import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, Radio, Space } from 'antd';
import dayjs, { Dayjs } from 'dayjs';

import Tinymc from '@/components/tinymc';
import UserSelect from '@/components/user-select';

import { store } from '@/store';

import { NoticeSendType, NoticeSendTypeObj, NoticeStatus } from '@/enum/notice';
import {
  sysMessageNotificationAdd,
  sysMessageNotificationUpdate
} from '@/services/base/jichumokuaixitongtongzhipeizhijiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        status: status.current
      };

      if (query.receiveObj) {
        query.receiveObj = JSON.stringify(query.receiveObj);
      }

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? sysMessageNotificationUpdate(query)
        : sysMessageNotificationAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );
  // 状态
  const status = useRef<NoticeStatus>();

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            const receiveObj = arg.rowData.receiveObj ? JSON.parse(arg.rowData.receiveObj) : [];
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              receiveObj
            });
          } else {
            form.resetFields();
            form.setFieldsValue({
              status: NoticeStatus.已发布,
              scheduleSend: NoticeSendType.立即发送
            });
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    status.current = NoticeStatus.待发布;
    form.submit();
  };

  // 保存并发布
  const onSaveAndPublish = () => {
    status.current = NoticeStatus.已发布;
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增通知',
          edit: '编辑通知',
          detail: '通知详情'
        }[args?.type as string]
      }
      extra={
        <Space>
          <Button
            type="primary"
            loading={submit.loading}
            disabled={submit.loading}
            onClick={onSave}
          >
            仅保存
          </Button>
          <Button
            type="primary"
            loading={submit.loading}
            disabled={submit.loading}
            onClick={onSaveAndPublish}
          >
            保存并发布
          </Button>
          <Button onClick={onCancel} disabled={submit.loading}>
            取消
          </Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="通知标题"
          name="notificationTitle"
          rules={[
            {
              required: true,
              message: '请输入通知标题'
            }
          ]}
        >
          <Input placeholder="请输入通知标题" />
        </Form.Item>
        <Form.Item
          label="通知内容"
          name="notificationContent"
          rules={[
            {
              required: true,
              message: '请输入通知内容'
            }
          ]}
        >
          <Tinymc />
        </Form.Item>

        <Form.Item label="指定用户(默认全部)" name="receiveObj">
          <UserSelect placeholder="请选择指定用户" mode="multiple" />
        </Form.Item>

        <Form.Item
          label="定时发送"
          name="scheduleSend"
          rules={[
            {
              required: true,
              message: '请选择定时发送'
            }
          ]}
        >
          <Radio.Group>
            {Array.from(NoticeSendTypeObj).map(([key, value]) => (
              <Radio value={key} key={key}>
                {value.text}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item dependencies={['scheduleSend']} noStyle>
          {({ getFieldValue }) => {
            const scheduleSend = getFieldValue('scheduleSend');

            if (scheduleSend === NoticeSendType.定时发送) {
              return (
                <Form.Item
                  label="定时发送时间"
                  name="scheduleTime"
                  rules={[
                    {
                      required: true,
                      message: '请输入定时发送时间'
                    }
                  ]}
                  getValueProps={(e) => {
                    return {
                      value: e ? dayjs(e) : undefined
                    };
                  }}
                  getValueFromEvent={(e) => {
                    return e ? (e as Dayjs).format('YYYY-MM-DD HH:mm:ss') : undefined;
                  }}
                >
                  <DatePicker placeholder="请选择定时发送时间" showTime />
                </Form.Item>
              );
            }

            return null;
          }}
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
